package com.android.project.mysql.connection;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.net.ParseException;
import android.util.Log;


public class SearchWord {

	JSONArray jArray;
	String result = null;
	InputStream is = null;
	StringBuilder sb=null;
    Random rand;
    int idWord;
    List<AssociationWord> list;
    HttpPost httppost ;
	
	public List<AssociationWord> find(List<NameValuePair> param){
		try{
			HttpClient httpclient = new DefaultHttpClient();
			 
			httppost = new HttpPost("http://10.0.2.2/webServiceWords.php");
			
			
	  	   //   httppost = new HttpPost("http://172.16.42.219:8080/webServiceWords.php");
	  	    
	  	     httppost.setEntity(new UrlEncodedFormEntity(param));
	  	     
	  	     HttpResponse response = httpclient.execute(httppost);
	  	     HttpEntity entity = response.getEntity();
	  	     is = entity.getContent();
	  	     
		}
		catch(Exception e){
	         Log.e("log_tag", "Error in http connection"+e.toString());
		}
		try{
		      BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
		      sb = new StringBuilder();
		      sb.append(reader.readLine() + "\n");
		      String line="0";
		      while ((line = reader.readLine()) != null) {
		                      sb.append(line + "\n");
		                   
		      }
	        is.close();
	        result=sb.toString();
      }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
      }
	  	//paring data
	  	list = new ArrayList<AssociationWord>();
	  	try{
	  	      jArray = new JSONArray(result);
	  	      JSONObject json_data=null;
	  	      for(int i=0;i<jArray.length();i++){
	  	            json_data = jArray.getJSONObject(i);     
	  	            Log.d("parola", " " + json_data.getString("word"));
	  	            AssociationWord w = new AssociationWord();
	  	            w.setWord(json_data.getString("word"));
	  	            list.add(w);        
	  	       }
	  	  }
  
	      catch(JSONException e1){
	    	  e1.printStackTrace();
	      } 
	  	 catch (ParseException e1) {
	  		 e1.printStackTrace();
	  	 }
  
		return list;
	}


}
